import React, { useEffect, useState } from 'react';
import { gql, useQuery } from '@apollo/client';
import { createLogger } from '../utils/logger';
import '../styles/QuestionRecommendations.css';

// 创建一个客户端专用的 logger
const logger =
  typeof window !== 'undefined'
    ? createLogger('QuestionRecommendations')
    : null;

const GET_RECOMMENDATION_QUESTIONS = gql`
  query GetRecommendationQuestions($id: ID!) {
    getProjectRecommendationQuestions(id: $id) {
      id
      status
      questions {
        question
        category
        sql
      }
    }
  }
`;

interface Question {
  question: string;
  category?: string;
  sql?: string;
}

interface QuestionRecommendationsProps {
  recommendationId?: string;
  onQuestionsLoaded?: (questions: Question[]) => void;
}

export const QuestionRecommendations: React.FC<
  QuestionRecommendationsProps
> = ({ recommendationId, onQuestionsLoaded }) => {
  const [lastPolledData, setLastPolledData] = useState<any>(null);

  const { loading, error, data, refetch } = useQuery(
    GET_RECOMMENDATION_QUESTIONS,
    {
      variables: { id: recommendationId },
      skip: !recommendationId,
      pollInterval: 2000,
      onCompleted: (data) => {
        logger.info('Query completed:', data);
        setLastPolledData(data);
      },
      onError: (error) => {
        logger.error('Query error:', error);
      },
    },
  );

  useEffect(() => {
    logger.info('Component mounted/updated', {
      recommendationId,
      hasData: !!data,
      loading,
      error: error?.message,
    });

    if (data?.getProjectRecommendationQuestions?.questions) {
      logger.info(
        'Questions found:',
        data.getProjectRecommendationQuestions.questions,
      );
      onQuestionsLoaded?.(data.getProjectRecommendationQuestions.questions);
    }

    // 如果有 recommendationId 但没有数据，尝试重新获取
    if (recommendationId && !data && !loading && !error) {
      logger.info('Triggering refetch for recommendationId:', recommendationId);
      refetch({ id: recommendationId });
    }
  }, [data, loading, error, recommendationId, onQuestionsLoaded, refetch]);

  // 渲染状态日志
  logger.debug('Render state:', {
    recommendationId,
    loading,
    error: error?.message,
    dataExists: !!data,
    lastPolledData: !!lastPolledData,
    questionCount: data?.getProjectRecommendationQuestions?.questions?.length,
    status: data?.getProjectRecommendationQuestions?.status,
  });

  if (!recommendationId) {
    return (
      <div className="question-recommendations-empty">
        No recommendation ID provided
      </div>
    );
  }

  if (loading && !lastPolledData) {
    return (
      <div className="question-recommendations-loading">
        Loading questions...
      </div>
    );
  }

  if (error) {
    return (
      <div className="question-recommendations-error">
        Error: {error.message}
        <button onClick={() => refetch()} className="retry-button">
          Retry
        </button>
      </div>
    );
  }

  const recommendation =
    data?.getProjectRecommendationQuestions ||
    lastPolledData?.getProjectRecommendationQuestions;
  if (!recommendation) {
    return (
      <div className="question-recommendations-empty">
        No data available
        <button onClick={() => refetch()} className="retry-button">
          Retry
        </button>
      </div>
    );
  }

  if (recommendation.status === 'generating') {
    return (
      <div className="question-recommendations-loading">
        Generating questions...
        <br />
        <small>This may take a few moments</small>
      </div>
    );
  }

  if (recommendation.status === 'failed') {
    return (
      <div className="question-recommendations-error">
        Failed to generate questions
        <br />
        <small>Please try again</small>
      </div>
    );
  }

  if (!recommendation.questions?.length) {
    return (
      <div className="question-recommendations-empty">
        No questions available
      </div>
    );
  }

  // 按类别分组显示问题
  const questionsByCategory: { [key: string]: Question[] } = {};
  recommendation.questions.forEach((question) => {
    const category = question.category || 'General';
    if (!questionsByCategory[category]) {
      questionsByCategory[category] = [];
    }
    questionsByCategory[category].push(question);
  });

  return (
    <div className="question-recommendations">
      {Object.entries(questionsByCategory).map(([category, questions]) => (
        <div key={category} className="category-section">
          <h3 className="category-title">{category}</h3>
          <div className="questions-list">
            {questions.map((question, index) => (
              <div key={`${category}-${index}`} className="question-item">
                <p className="question-text">{question.question}</p>
                {question.sql && (
                  <code className="question-sql">{question.sql}</code>
                )}
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};
